package com.oa.modules.approvalsec1.controller;

import java.io.File;
import java.lang.reflect.Array;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import com.oa.common.utils.*;
import com.oa.modules.approvalsec1.entity.CloudVideoEntity;
import com.oa.modules.approvalsec1.entity.RoomStoreEntity;
import com.oa.modules.approvalsec1.service.CloudVideoService;
import com.oa.modules.approvalsec1.service.RoomStoreService;
import com.oa.modules.approvalsec1.socket.WebSocketServer;
import com.oa.modules.sys.controller.AbstractController;
import com.oa.modules.sys.entity.SysRoleEntity;
import com.oa.modules.sys.service.SysRoleService;
import com.oa.modules.sys.service.SysUserRoleService;
import freemarker.template.TemplateDateModel;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.oa.modules.approvalsec1.entity.ExplorationCloudEntity;
import com.oa.modules.approvalsec1.service.ExplorationCloudService;


/**
 * 云探勘表
 *
 * @author jiangwei
 * @email 785297226@qq.com
 * @date 2021-04-06 14:12:59
 */
@RestController
@RequestMapping("exploration/cloud")
@Api(tags = "云探勘表相关接口")
public class ExplorationCloudController extends AbstractController {
    @Autowired
    private ExplorationCloudService explorationCloudService;
    @Autowired
    private CloudVideoService cloudVideoService;
    @Autowired
    private RoomStoreService roomStoreService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private PdfUtil pdfUtil;

    private static void findFile(List<ExplorationCloudEntity> list) throws Exception {
        for (ExplorationCloudEntity explorationCloud : list) {
            String fileUrl = explorationCloud.getMatterUrl();
            if (fileUrl != null && !"".equals(fileUrl)) {
                if (fileUrl.indexOf(",") >= 0) {
                    String[] fileUrls = fileUrl.split(",");
                    for (String file : fileUrls) {
                        String fileType = "";
                        String type = file.indexOf(".") != -1 ? file.substring(file.lastIndexOf(".") + 1, file.length()) : null;
                        if ("GIF".equals(type.toUpperCase()) || "PNG".equals(type.toUpperCase()) || "JPG".equals(type.toUpperCase()) || "JPEG".equals(type.toUpperCase())) {
                            fileType = "image";
                        } else {
                            fileType = "file";
                        }
                        String[] path = file.split("/");
                        String destDir = "";
                        if (fileType.equals("image")) {
                            destDir = "C:/Users/Administrator/Desktop/上传文件/image/" + path[path.length - 2];
                        } else {
                            destDir = "C:/Users/Administrator/Desktop/上传文件/file/" + path[path.length - 2];
                        }
                        File filePath = new File(destDir);
                        if (!filePath.exists() && !filePath.isDirectory()) {
                            filePath.mkdir();
                        }
                        FileUtil.downloadByUrl(file, path[path.length - 1], destDir);
                    }
                } else {
                    if (fileUrl != null && !"".equals(fileUrl)) {
                        String fileType = "";
                        String type = fileUrl.indexOf(".") != -1 ? fileUrl.substring(fileUrl.lastIndexOf(".") + 1, fileUrl.length()) : null;
                        if ("GIF".equals(type.toUpperCase()) || "PNG".equals(type.toUpperCase()) || "JPG".equals(type.toUpperCase()) || "JPEG".equals(type.toUpperCase())) {
                            fileType = "image";
                        } else {
                            fileType = "file";
                        }
                        String[] path = fileUrl.split("/");
                        String srcPath = fileUrl;
                        String destDir = "";
                        if (fileType.equals("image")) {
                            destDir = "C:/Users/Administrator/Desktop/上传文件/image/" + path[path.length - 2];
                        } else {
                            destDir = "C:/Users/Administrator/Desktop/上传文件/file/" + path[path.length - 2];
                        }
                        File filePath = new File(destDir);
                        if (!filePath.exists() && !filePath.isDirectory()) {
                            filePath.mkdir();
                        }
                        FileUtil.downloadByUrl(fileUrl, path[path.length - 1], destDir);
                    }
                }
            }
        }
    }

    @PostMapping("/testFile")
    @ApiOperation(value = "查询")
    public R testFile(@RequestBody Map<String, Object> reqParams) throws Exception {
        List<ExplorationCloudEntity> explorationCloud = explorationCloudService.list();
        findFile(explorationCloud);
        return R.ok().put("success", explorationCloud);
    }

    /**
     * 列表
     */
    @GetMapping("/list")
    @ApiOperation(value = "列表")
    public R list(@RequestParam Map<String, Object> params) {
        if (!"".equals(params.get("roleId")) && params.get("roleId") != null) {
            SysRoleEntity roleEntity = sysRoleService.getById((String) params.get("roleId"));
            System.out.println(roleEntity.getRoleName());
            params.put("type", roleEntity.getRoleName());
        } else {
            params.put("type", "");
        }
        PageUtils page = explorationCloudService.queryPage(params);
        if (page.getList() != null && page.getList().size() > 0) {
            for (int i = 0; i < page.getList().size(); i++) {
                ExplorationCloudEntity explorationCloud = (ExplorationCloudEntity) page.getList().get(i);
                explorationCloud.setCloudVideoEntityList(cloudVideoService.list(new QueryWrapper<CloudVideoEntity>().eq("cloud_id", explorationCloud.getId())));
                if(org.springframework.util.StringUtils.hasText(explorationCloud.getRoomNum())){
                    RoomStoreEntity roomStore = roomStoreService.getOne(new QueryWrapper<RoomStoreEntity>().eq("ROOM_NUM",explorationCloud.getRoomNum()));
                    explorationCloud.setCreateDate(roomStore.getCreateDate());
                }else{
                    explorationCloud.setCreateDate(null);
                }
            }
        }
        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @GetMapping("/aWxInfo")
    @ApiOperation(value = "信息")
    public R aWxInfo(@RequestParam  String id) {
        ExplorationCloudEntity cloud = explorationCloudService.getById(id);
        ArrayList result = new ArrayList<>();
        List<String> list = new ArrayList<>();
        List<String> list2 = new ArrayList<>();
        if (StringUtils.isNotEmpty(cloud.getSignPath())) {
            list = Arrays.asList(cloud.getSignPath().split(","));
        }
        if (StringUtils.isNotEmpty(cloud.getSealPath())) {
            list2 = Arrays.asList(cloud.getSealPath().split(","));
        }
        if (list2 != null && list2.size() > 0) result.addAll(list2);
        if (list != null && list.size() > 0) result.addAll(list);
        cloud.setAllUrl(result);
        return R.ok().put("data", cloud);
    }

    /**
     * 信息
     */
    @GetMapping("/wxInfo/{id}")
    @ApiOperation(value = "信息")
    public R wxInfo(@PathVariable("id")  String id) {
        ExplorationCloudEntity cloud = explorationCloudService.getById(id);
        ArrayList result = new ArrayList<>();
        List<String> list = new ArrayList<>();
        List<String> list2 = new ArrayList<>();
        if (StringUtils.isNotEmpty(cloud.getSignPath())) {
            list = Arrays.asList(cloud.getSignPath().split(","));
        }
        if (StringUtils.isNotEmpty(cloud.getSealPath())) {
            list2 = Arrays.asList(cloud.getSealPath().split(","));
        }
        if (list2 != null && list2.size() > 0) result.addAll(list2);
        if (list != null && list.size() > 0) result.addAll(list);
        cloud.setAllUrl(result);
        return R.ok().put("data", cloud);
    }



    /**
     * 信息
     */
    @GetMapping("/info/{id}")
    @ApiOperation(value = "信息")
    public R info(@PathVariable("id") String id) {
        ExplorationCloudEntity explorationCloud = explorationCloudService.getById(id);
        if (explorationCloud != null) {
            explorationCloud.setCloudVideoEntityList(cloudVideoService.list(new QueryWrapper<CloudVideoEntity>().eq("cloud_id", explorationCloud.getId())));
            explorationCloud.setRoomStoreEntityList(roomStoreService.list(new QueryWrapper<RoomStoreEntity>().eq("EXPLORATION_CLOUD_ID", explorationCloud.getId()).orderByAsc("NUM_TIMES")));
        }
        return R.ok().put("explorationCloud", explorationCloud);
    }


    /**
     * 保存
     */
    @PostMapping("/save")
    @ApiOperation(value = "保存")
    public R save(@RequestBody ExplorationCloudEntity explorationCloud) {
        explorationCloud.setId(AppUtils.getUUID());
        explorationCloud.setCreateDate(new Date());
        if(explorationCloud.getExplorationType()==null||explorationCloud.getExplorationType()==0){
            explorationCloud.setExplorationType(1);
        }
        explorationCloud.setResultUrl(null);
        explorationCloudService.save(explorationCloud);
        return R.ok().put("clouId",explorationCloud.getId());
    }


    @GetMapping("/test")
    public R test() {
        explorationCloudService.test();
        return R.ok();
    }

    /**
     * 修改
     */
    @PostMapping("/update")
    @ApiOperation(value = "修改")
    public R update(@RequestBody ExplorationCloudEntity explorationCloud) {
        if (explorationCloud.getMatterUrl() != null) {
            ExplorationCloudEntity exploration = explorationCloudService.getById(explorationCloud.getId());
            if (exploration != null && exploration.getMatterUrl() != null && !exploration.getMatterUrl().equals("")) {
                if (!"4".equals(exploration.getIsHandler())) {
                    //前台都传matterUrl字段中，后台判断。
                    //如果次数是1   那就直接拼接进matterUrl字段。
                    //如果次数是2   那就拼接进matterUrl2
                    if (exploration.getMatterUrl() != null && !exploration.getMatterUrl().equals("")) {
                        String matterUrl = exploration.getMatterUrl() + "," + explorationCloud.getMatterUrl();
                        explorationCloud.setMatterUrl(matterUrl);
                    } else {
                        String matterUrl = explorationCloud.getMatterUrl();
                        explorationCloud.setMatterUrl(matterUrl);
                    }
                } else {
                    if (exploration.getMatterUrl2() != null && !exploration.getMatterUrl2().equals("")) {
                        String matterUrl = exploration.getMatterUrl2() + "," + explorationCloud.getMatterUrl();
                        explorationCloud.setMatterUrl2(matterUrl);
                        explorationCloud.setMatterUrl(exploration.getMatterUrl());
                    } else {
                        String matterUrl = explorationCloud.getMatterUrl();
                        explorationCloud.setMatterUrl2(matterUrl);
                        explorationCloud.setMatterUrl(exploration.getMatterUrl());
                    }
                }
            }
        }
        explorationCloud.setUpdateDate(new Date());
        explorationCloudService.updateById(explorationCloud);
        return R.ok();
    }

    /**
     * 视频结束后发送文件
     *
     * @return
     */
    @PostMapping("/saveFile")
    public R saveFile(@RequestBody ExplorationCloudEntity entity) {
        //更新表数据
        ExplorationCloudEntity cloudEntity = explorationCloudService.getById(entity.getId());
        String docPath = entity.getDocPath();
        String pdfPath = "";
        if (docPath != null && !"".equals(docPath)) {
            if (cloudEntity.getDocPath() != null && !"".equals(cloudEntity.getDocPath())) {
                cloudEntity.setDocPath(cloudEntity.getDocPath() + "," + docPath);
            } else {
                cloudEntity.setDocPath(docPath);
            }
            //docx文件转成pdf
            pdfPath = explorationCloudService.toPdf(docPath);
            if (cloudEntity.getPdfPath() != null && !"".equals(cloudEntity.getPdfPath())) {
                cloudEntity.setPdfPath(cloudEntity.getPdfPath() + "," + pdfPath);
            } else {
                cloudEntity.setPdfPath(pdfPath);
            }
        }
        explorationCloudService.updateById(cloudEntity);
        explorationCloudService.sendFile(cloudEntity);
        return R.ok();
    }


    @PostMapping("/pushFile")
    public R pushFile(@RequestBody ExplorationCloudEntity entity) {
        //更新表数据
        ExplorationCloudEntity cloudEntity = explorationCloudService.getById(entity.getId());
        String docPath = entity.getDocPath();
        String pdfPath = "";
        if (docPath != null && !"".equals(docPath)) {
            if (cloudEntity.getDocPath() != null && !"".equals(cloudEntity.getDocPath())) {
                cloudEntity.setDocPath(cloudEntity.getDocPath() + "," + docPath);
            } else {
                cloudEntity.setDocPath(docPath);
            }
            //docx文件转成pdf
            pdfPath = explorationCloudService.toPdf(docPath);
            if (cloudEntity.getPdfPath() != null && !"".equals(cloudEntity.getPdfPath())) {
                cloudEntity.setPdfPath(cloudEntity.getPdfPath() + "," + pdfPath);
            } else {
                cloudEntity.setPdfPath(pdfPath);
            }
        }
        explorationCloudService.updateById(cloudEntity);

        //获取房间信息
        RoomStoreEntity roomStore = roomStoreService.getOne(new QueryWrapper<RoomStoreEntity>().eq("room_num", cloudEntity.getRoomNum()));
        //根据房间号获取用户权限进行推送
//        SysUserRoleEntity userRoleEntity = sysUserRoleService.getOne(new QueryWrapper<SysUserRoleEntity>().eq("user_id", roomStore.getPushId()));
        //存储需要推送的文件
        ArrayList<Map<String, String>> maps = new ArrayList<>();
        String[] files = pdfPath.split(",");
        for (String file : files) {
            HashMap<String, String> map = new HashMap<>();
            map.put("type", cloudEntity.getType());
            map.put("file", file);
            maps.add(map);
        }
        Gson gson = new Gson();
        WebSocketServer.sendMessage2(roomStore.getPushId(), gson.toJson(maps));
        return R.ok();
    }

    /**
     * 删除
     */
    @PostMapping("/delete")
    @ApiOperation(value = "删除")
    public R delete(@RequestBody String[] ids) {
        explorationCloudService.removeByIds(Arrays.asList(ids));
        return R.ok();
    }

    /**
     * 历史记录
     *
     * @param params
     * @return
     */
    @GetMapping("/history")
    @ApiOperation(value = "查询历史列表")
    public R history(@RequestParam Map<String, Object> params) {
        PageUtils page = explorationCloudService.findHistory(params);
        if (page.getList() != null && page.getList().size() > 0) {
            for (int i = 0; i < page.getList().size(); i++) {
                ExplorationCloudEntity explorationCloud = (ExplorationCloudEntity) page.getList().get(i);
                explorationCloud.setCloudVideoEntityList(cloudVideoService.list(new QueryWrapper<CloudVideoEntity>().eq("cloud_id", explorationCloud.getId())));
            }
        }
        return R.ok().put("page", page);
    }

    /**
     * 签名
     *
     * @return
     */
    @PostMapping("/sign/signature")
    public R signature(@RequestBody Map<String, Object> params) {
        String path = explorationCloudService.signature(params);
        return R.ok().put("path", path);
    }

    /**
     * 印章
     *
     * @return
     */
    @PostMapping("/seal")
    public R seal(@RequestBody Map<String, Object> params) {
        String id = (String) params.get("id");
        String target = (String) params.get("target");
        ExplorationCloudEntity cloudEntity = explorationCloudService.getOne(new QueryWrapper<ExplorationCloudEntity>().eq("ID", id));
        String path = pdfUtil.imgToPdf(target);
        if(StringUtils.isNotEmpty(cloudEntity.getSealPath())){
            cloudEntity.setSealPath(cloudEntity.getSealPath()+","+path);
        }else{
            cloudEntity.setSealPath(path);
        }
        explorationCloudService.updateById(cloudEntity);
        return R.ok();
    }

    /**
     * 获取已签字的文件
     */
    @GetMapping("/signatureFile")
    public R signatureFile(String id) {
        ExplorationCloudEntity cloudEntity = explorationCloudService.getById(id);
        String sign = cloudEntity.getSignPath();
        String seal = cloudEntity.getSealPath();
        StringBuilder builder = new StringBuilder();
        if (StringUtils.isNotEmpty(cloudEntity.getSignPath())) {
            builder.append(cloudEntity.getSignPath());
        }
        if (StringUtils.isNotEmpty(cloudEntity.getSealPath())) {
            if (builder != null || builder.length() != 0) {
                builder.append(","+cloudEntity.getSealPath());
            }else{
                builder.append(cloudEntity.getSealPath());
            }
        }
        return R.ok().put("data",builder.toString());
    }
}
